package mianshi.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/11/16 16:41
 */
//阻挡反射
public class LazyMan3 {
    private static boolean flag = false;

    private LazyMan3() {
        synchronized (LazyMan3.class) {
            if (flag == false) {
                flag = true;
            }else {
                throw new RuntimeException("不要试图用反射破坏单例模式");
            }
        }
    }

    private volatile static LazyMan3 LazyMan3;

    public static LazyMan3 getInstance() {
        if (LazyMan3 == null) {
            synchronized (LazyMan.class) {
                if (LazyMan3 == null) {
                    LazyMan3 = new LazyMan3();
                }
            }
        }
        return LazyMan3;
    }
}

class Demo03 {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        LazyMan3 instance = LazyMan3.getInstance();
        //反射
        Constructor<LazyMan3> declaredConstructor = LazyMan3.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyMan3 instance2 = declaredConstructor.newInstance();


        System.out.println(instance == instance2);

    }
}